#include "TcpServer.h"
#include "TcpConnection.h"
#include "ThreadPool.h"
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

ThreadPool pool(3, 8);

class MyTask {
private:
    string _msg;
    const TcpConnection::TcpConnectionPtr &_con;

public:
    MyTask(const string &msg, const TcpConnection::TcpConnectionPtr& con) :
            _msg(msg),
            _con(con) {}

    void process() {
        cout << ">>>>recv from client : " << this->_msg << endl;
        this->_con->send("对不起，做不到\n");
    }
};



void onNewConnection(const TcpConnection::TcpConnectionPtr &con) {
    cout << con->toString() << " has connected!!!" << endl;
}

void onMessage(const TcpConnection::TcpConnectionPtr &con) {
    string msg = con->receive();

    MyTask task(msg, con);
    pool.addTask(std::bind(&MyTask::process, &task));
}

void onClose(const TcpConnection::TcpConnectionPtr &con) {
    cout << con->toString() << " has closed!!!" << endl;
}


int main() {
    pool.start();

    TcpServer tcpServer("127.0.0.1", 8888);
    tcpServer.setAllCallback(std::move(bind(onNewConnection, std::placeholders::_1)),
                             std::move(bind(onMessage, std::placeholders::_1)),
                             std::move(bind(onClose, std::placeholders::_1)));
    tcpServer.start();

    return 0;
}
